<?php

/**
 *
 * Class JSSDK
 */

class jssdk_helper
{
    private static $appId;
    private static $appSecret;
    private static $type;

    /**
     * 初始化参数
     */
    private static function init() {
        self::$appId     = C('WX_CONFIG.APPID');
        self::$appSecret = C('WX_CONFIG.APPSECRET');
        self::$type      = 1;// 1公众号 2：企业号 3:普通用户
    }

    /**
     * 获取jssdk 签名
     * @return array
     */
    public static function get_sign_package() {
        self::init();

        $jsapiTicket = self::get_jsapi_ticket();
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = self::create_nonce_str();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => self::$appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    /**
     * 创建随机字符串
     * @param int $length
     * @return string
     */
    private static function create_nonce_str($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 获取数据库中的jsapi_ticket
     * @return unknown
     */
    private static function get_jsapi_ticket() {
        $ticket_info = _uri('jsapi_ticket', array('ticket_type' => self::$type));
        if ($ticket_info) {
            // 存在调用数据库中的ticket
            if ($ticket_info['ticket'] && $ticket_info['expires_time'] > time()) {
                $ticket = $ticket_info['ticket'];
            } else {
                $res = self::get_jsapi_ticket_by_api();
                $info = array('ticket'=>$res['ticket'], 'ticket_type' => self::$type, 'expires_time' => $res['expires_in'] + time());
                M('jsapi_ticket')->where("id={$ticket_info['id']}")->save($info);
                $ticket = $res['ticket'];
            }

        } else {
            // 不存在创建
            $res = self::get_jsapi_ticket_by_api();
            $info = array('ticket'=>$res['ticket'], 'ticket_type' => self::$type, 'expires_time' => $res['expires_in'] + time());
            M('jsapi_ticket')->add($info);
            $ticket = $res['ticket'];
        }

        return $ticket;
    }

    /**
     *  通过接口获取jsapi_ticket
     */
    private function get_jsapi_ticket_by_api()
    {
        $accessToken = self::get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
        // 如果是企业号用以下 URL 获取 ticket
        // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
        $res = json_decode(self::http_get($url), true);
        if (!$res) exit('获取jsapi_ticket失败');
        return $res;
    }

    /**
     * 获取数据库中的access_token
     * @return unknown
     */
    public static function get_access_token() {
        self::init();
        $connect_info = _uri('connect_weixin', array('token_type' => self::$type));
        if ($connect_info) {
            // 存在，调用数据库的token
            if ($connect_info['access_token'] && $connect_info['expires_time'] > time()) {
                $access_token = $connect_info['access_token'];
            } else {
                // 过期更新
                $res = self::get_access_token_by_api();
                $info = array('access_token' => $res['access_token'], 'expires_time' => $res['expires_in'] + time());
                M('connect_weixin')->where("id={$connect_info['id']}")->save($info);
                $access_token = $res['access_token'];
            }

        } else {
            // 不存在，获取并创建
            $res = self::get_access_token_by_api();
            $info = array('token_type' => self::$type, 'access_token' => $res['access_token'], 'expires_time' => $res['expires_in'] + time());
            M('connect_weixin')->add($info);
            $access_token = $res['access_token'];
        }

        return $access_token;
    }

    /**
     * 通过接口获取access_token
     * @return mixed
     */
    private static function get_access_token_by_api()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.self::$appId.'&secret='.self::$appSecret;
        $res = json_decode(self::http_get($url), true);
        if (!$res) exit('获取access_token失败，错误代码'.__FILE__);
        return $res;
    }

    /**
     * @param $url
     * @return mixedcurl
     */
    private static function http_get($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    /**
     * 从微信服务器下载图片
     * @param $server_id
     */
    public static function download_img($media_id)
    {
        $url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.self::get_access_token().'&media_id='.$media_id;
        $content = http_request($url, 'get');
        $file_path = '';
        if ($content) {
            $file_path = './uploads/images/'.$media_id.'.jpg';
            $res = file_put_contents($file_path, $content);
            if (!$res) {
                return false;
            }
        }
        return trim($file_path, '.');
    }
    
    /**
     * 从微信服务器下载图片(添加帖子使用)
     * @param $server_id
     */
    public static function download_img_card($media_id)
    {
        $url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.self::get_access_token().'&media_id='.$media_id;
        $content = http_request($url, 'get');
        $file_path = '';
        $file_path_return = '';
        if ($content) {
            $file_path_return = './images/'.$media_id.'.jpg';
            $file_path = './uploads/images/'.$media_id.'.jpg';
            $res = file_put_contents($file_path, $content);
            if (!$res) {
                return false;
            }
        }
        return trim($file_path_return, '.');
    }
}

